<template>
	<view class="content">
		<view style="width: 100%;">
      <div v-if="loading" style="display: flex; flex-direction: column; align-items: center; padding: 200rpx 0;">
        <u-loading></u-loading>
        <div style="margin-top: 30rpx; color: #666;">加载中...</div>
      </div>
			<u-index-list v-else :scrollTop="scrollTop"  :active-color="'#3CC51F'"  :index-list="vuex_contactIndex">
				<view v-for="(item, index) in myFirendList" :key="index" style="width: 100%;">
					<u-index-anchor :index="item.firstLetter"/>
						<view v-for="friend in item.friends" :key="friend.id" class="list-cell" @tap="goSelect(friend)">
							<view :style="{opacity: friend.disabled ? 0.5 : 1}">
                <image src="/static/svg/mention-check.svg" style="width: 42rpx; height: 42rpx; margin-right: 24rpx; " v-if="friend.isChecked"/>
                <image src="/static/svg/mention-uncheck.svg" style="width: 42rpx; height: 42rpx; margin-right: 24rpx; " v-else/>
							</view>
							<view>
								<static-image :src="friend.avatar"  mode="aspectFill" :width="80" :height="80" :radius="12">
								</static-image>
							</view>
							<view  class="list-cell-name" style="flex: 1" >{{friend.name}}</view>
						</view>
				</view>
			</u-index-list>
      <view style="height: 120rpx"></view>
        <view class="submit" style="position: fixed; bottom: 0; left: 0; right: 0; z-index: 1; padding: 24rpx; background-color: #fff;">
          <u-button type="success" :disabled="!selectedUser.length" @tap="addUserInGroup">确认</u-button>
        </view>
		</view>
		
		<template v-if="groupNameModal">
			<create-group-pop ref="groupPop"
						:windowHeight="windowHeight"
						:groupModelFlag="groupNameModal"
						@submitCreate="buildChatGroup"
						@closeModel="closeModel"></create-group-pop>
		</template>
		
	</view>
</template>

<script>
import searchInput from '@/components/searchInput/index.vue';
import createGroupPop from '@/components/create-group-pop/create-group-pop.vue';
export default {
	components:{searchInput,createGroupPop},
	data() {
		return {
      loading: true,
			scrollTop: 0,
			myFirendList:[],
			selectedUser: [],
			currentUserId:'',
			groupNameModal:false,
			chatGroupName:'',
			windowHeight:0,
			butOptionType:0,
      submiting: false
		};
	},
	
	created () {
		this.windowHeight=this.$u.sys().windowHeight;
	},
	
	async onLoad (options) {
    this.groupId = Number(options.chatGroupId)
		this.currentUserId=this.vuex_userInfo.id;
    await this.$store.dispatch('refreshContactList')
    await this.$store.dispatch('vuex_current_group', this.groupId)
    this.myFirendList = this.vuex_contactListData.map(s => ({
      ...s,
      friends: s.friends.map(q => {
        const isIn = this.vuex_current_group.user_group_relations.find(s => s.user_id === q.id && s.right !== 'REJECT')
        return {
          ...q,
          isChecked: !!isIn,
          disabled: !!isIn
        }
      })
    }))
    this.loading = false
	},
	
	methods: {
    goSelect (item) {
      if (item.disabled) return
      if (this.selectedUser.includes(item)) {
        item.isChecked = false
        this.selectedUser.splice(this.selectedUser.indexOf(item), 1)
      } else {
        item.isChecked = true
        this.selectedUser.push(item)
      }
    },
		//初始化通讯录列表
		getMyFriendList:function(){
		   let that=this;
		   let param={};
		    that.$u.api.imUser.getMyFriendList(param).then(res => {
				if(res.code==200){
					//console.log("获取通讯录结果",res);
					let data=res.data;
					let indexList= data.myFriendsIndexList;
					if(indexList!=null&&indexList!=undefined){
						that.indexList=indexList;
					}
					let myFriendList= data.myFriendList;
					if(myFriendList!=null&&myFriendList!=undefined){
						that.myFirendList=myFriendList;
					}
				}
			})	   
		},
		
		//发起群聊
		async addUserInGroup(){
      if (this.selectedUser.length < 1) return
      
      await this.$u.api.chatGroup.inviteGroup({
        group_id: this.groupId,
        user_ids: this.selectedUser.map(s => s.id)
      })
      await this.$store.dispatch('vuex_current_group', this.groupId)
      uni.navigateBack()
		},
		closeModel:function(){
			this.groupNameModal=false;
		},
		buildChatGroup:function(newGroup){
			let that=this;
			let selectedFriends=[];
			that.selectedUser.forEach((item) => {
			  selectedFriends.push(item);
			})
			selectedFriends.push(that.currentUserId);
			console.log("选择人员",selectedFriends);
			that.globalUtil.utilLoading("正在发起群聊...",true);
			let obj={user_ids:selectedFriends, is_multi: 'GROUP'};
			let param=Object.assign(obj,newGroup);
			console.log("发起群聊参数",param);
			that.$u.api.chatGroup.launchChatGroup(param).then(res => {	
			  console.log("发起群聊响应结果",res);
			  if (res!=null&&res.data!=null&&res.code===200) {
			       that.globalUtil.utilAlert("创建成功!","success");  
				   that.selectedUser.clear();
				   let chatGroupId=res.data.id;
				   let param="?chatGroupId="+chatGroupId;
				   let _url="/pages/chat/chatGroup/chatting";
				   let chatUrl=_url+param;
				   uni.navigateTo({
				     url: chatUrl,
				     success() {
				     
				     }
				   });
				   return;
			  }else{
			    uni.hideLoading();
			    that.globalUtil.utilAlert("发起聊天失败!","error");
			    return;
			  }
			}).catch(res => {
			  uni.hideLoading();
			  that.globalUtil.utilAlert("发起聊天失败!","error");
			  console.log("会话列表加载触发异常",res);
			})
		},
	},
	onPageScroll(e) {
		this.scrollTop = e.scrollTop;
	}
};
</script>

<style lang="scss" scoped>
.content {
	height: 100%;
	.slot-wrap {
		display: flex;
		align-items: center;
		padding: 0 30rpx; 
	}
	.list-cell {
		display: flex;
		box-sizing: border-box;
		width: 100%;
		padding: 10px 24rpx;
		overflow: hidden;
		color: #323233;
		font-size: 28rpx;
		line-height: 48rpx;
		background-color: #fff;
		align-items: center;
		image {
			width: 76rpx;
			height: 76rpx;
			border-radius: 12rpx;
			flex: 0 0 76rpx;
		}
		&-name{
			padding-left: 20rpx;
		}
	}
}
</style>
